import {cookies} from "next/headers";
import {addDays} from "date-fns";
import {Users} from "@/lib/db/types";
import {verifyToken} from "@/lib/utils";

/**
 * 设置session信息系
 * @param token
 */
export const setSession = async (token:string) => {

    const ies = await cookies();
    ies.set("Authorization", token, {
        httpOnly: true,
        secure: false,
        path: "/",
        sameSite: "strict",
        expires: addDays(new Date(), 7)
    });

}

/**
 * 获取会话信息
 */
export const getSession = async () => {

    const ies = await cookies();
    const authorization = ies.get("Authorization");
    if(!authorization || !authorization.value){
        return null;
    }
    try {
        const payload = await verifyToken(authorization.value);

        return payload as Omit<Exclude<Users,null>, "password"|"createdAt"|"updatedAt">;
    }catch (e) {
        console.log(e);
    }
    return null;
}

